package com.juli.aimanager.sysconfig.interceptor;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;

public class CheckLoginFilter implements Filter{
	
	private String filter_exclude;
	
	 private final Logger log = Logger.getLogger(this.getClass());

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) sRequest;
        HttpServletResponse response = (HttpServletResponse) sResponse;
       
     // 获得用户请求的URI
        String path = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = path.substring(contextPath.length());
        
        if(checkfilter(url)){
        	 String username =  (String)request.getSession().getAttribute("userId");   
             if(username == null){  
            	 log.info("请求的IP地址为:========="+request.getRemoteAddr());
                 log.info("Interceptor：跳转到login页面！");  
                 request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);  
                 
             } 
        }
        
        
        chain.doFilter(request, response);
	}
	
	private boolean checkfilter(String url)
	  {
		boolean bool=true;
	    String[] inc = this.filter_exclude.split(";");
	    for (int i = 0; i < inc.length; i++) {
	      if (url.equals(inc[i])) {
	            bool=false;
	            break;
	      }
	    }
	   
	    return bool;
	  }
	

	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		filter_exclude=config.getInitParameter("filter_exclude");
		System.out.println(filter_exclude);
	}

}
